import requests
import json

from src.Business.wechat.WxPayV3.WxPayTool import WxPayTool


class WxPayApi:
    wx = None
    url = "https://api.mch.weixin.qq.com"

    def __init__(self, **kwargs):
        self.wx = WxPayTool(**kwargs)

    def pay_transactions(self, **kwargs):
        """
        支付接口
        :param kwargs:
        :return:
        """
        post_data = kwargs.get("post_data")
        api_url = "/v3/pay/transactions/jsapi"
        url = self.url + api_url
        payload = json.dumps(post_data)
        headers, timestamp_str, nonce_str = self.wx.get_headers(data=payload, method="POST", url=api_url)
        response = requests.request("POST", url, headers=headers, data=payload)
        return (eval(response.text), timestamp_str, nonce_str)

    def refunds(self, **kwargs):
        """
        退款
        """
        post_data = kwargs.get("post_data")
        api_url = "/v3/refund/domestic/refunds"
        url = self.url + api_url
        payload = json.dumps(post_data)
        headers, timestamp_str, nonce_str = self.wx.get_headers(data=payload, method="POST", url=api_url)
        response = requests.request("POST", url, headers=headers, data=payload)
        return (eval(response.text), timestamp_str, nonce_str)

    def transactions_select(self, out_trade_no, mchid):
        """
        查询订单
        """
        # post_data = kwargs.get("post_data")
        api_url = f"/v3/pay/transactions/out-trade-no/{out_trade_no}?mchid={mchid}"
        url = self.url + api_url
        payload = ""
        headers, timestamp_str, nonce_str = self.wx.get_headers(data=payload, method="GET", url=api_url)
        response = requests.request("GET", url, headers=headers, data=payload)
        return (eval(response.text), timestamp_str, nonce_str)

    def get_certificates(self):
        """
        获取平台证书
        """
        api_url = "/v3/certificates"
        url = self.url + api_url
        payload = ""
        headers, timestamp_str, nonce_str = self.wx.get_headers(data=payload, method="GET", url=api_url)
        response = requests.request("GET", url, headers=headers, data=payload)
        return eval(response.text)


if __name__ == '__main__':
    wx_info = {
        "mchid": "1664546599",  # 商户id
        "serial_no": "77FE40E4735D85ECA2BC94AA983620E7281720FA",  # 证书编号
        "secret": "72347ac4a69093ddefc05de2c4910f34",  # 证书密钥
    }
    wx = WxPayApi(**wx_info)
    result, timestamp, noce_str = wx.transactions_select(out_trade_no="455191DB87114C45827B8F62E2662C52",
                                                         mchid="1664546599")
    print(result)
